package com.mytijian.code.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.mytijian.code.dto.QueryItemIdByCodeResult;
import com.mytijian.code.exceptions.MashangExceptionEnum;
import com.mytijian.code.model.Mcode;
import com.mytijian.code.model.MerchantOrder;
import com.mytijian.code.param.alihalt.QueryItemIdByCodeParam;
import com.mytijian.code.param.alihalt.ToTBAvailableParam;
import com.mytijian.code.param.alihalt.ToTBConsumeParam;
import com.mytijian.exception.BizException;

/**
 * Created by shjh on 2017/9/21.
 */
@Service
public class MerchantServiceImpl implements MerchantService {
	
    private Logger logger = LoggerFactory.getLogger(MerchantServiceImpl.class);

    @Autowired
    private ConsumeCodeService consumeCodeService;
    @Autowired
    private CodeService codeService;
    @Autowired
    private MerchantOrderService orderService;

    @Override
    public void available(ToTBAvailableParam param) {
        logger.info("阿里健康对接系统码校验param: " + JSON.toJSONString(param));
        consumeCodeService.available(param);
    }

    @Override
    public void consume(ToTBConsumeParam param) {
        logger.info("阿里健康对接系统电子码核销param: " + JSON.toJSONString(param));
        consumeCodeService.consume(param);
    }

    @Override
    public QueryItemIdByCodeResult queryItemIdByCode(QueryItemIdByCodeParam param) {
        logger.info("阿里健康对接系统通过电子码查询天猫商品ID param: " + JSON.toJSONString(param));
        QueryItemIdByCodeResult result = getItemIdByCode(param);
        logger.info("阿里健康对接系统通过电子码查询天猫商品ID result: " + JSON.toJSONString(result));
        return result;
    }
    
    /**
     * 通过电子码查询天猫商品ID(阿里健康对接系统调用)
     */
    private QueryItemIdByCodeResult getItemIdByCode(QueryItemIdByCodeParam param) {
    	Mcode mcode = codeService.getCodeByCode(param.getCode());
        if (mcode == null) {
            throw new BizException(MashangExceptionEnum.CODE_NOT_EXIST);
        }
        MerchantOrder tmOrder = orderService.getOrderByOuterId(mcode.getOuterId());
        QueryItemIdByCodeResult result = new QueryItemIdByCodeResult();
        result.setItemId(tmOrder.getOuterIdSKU());
        return result;
    }
}
